﻿using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace SGP.BlogEngine.ServerAssetSelector
{

    public class BrowseItem
    {
        public string Name { get; set; }
        public string Path { get; set; }
        public bool IsDirectory { get; set; }
        public string Icon { get; set; }

        public BrowseItem()
        {
        }
    }

    public class FileBrowserHandler
    {

        private const string UPDIRICON = "../dir_up.png";
        private const string DIRICON = "../dir.png";


        public string CurrentDirectory { get; set; }
        public string FolderIcon { get; set; }
        public string FileIcon { get; set; }
        private static string _RootDirectory;
        public FileBrowserHandler(string currentDir, string rd)
        {
            CurrentDirectory = currentDir;
            _RootDirectory = rd;
        }

        public string Browse()
        {
            List<BrowseItem> result = new List<BrowseItem>();
            try
            {
               
                DirectoryInfo di = new DirectoryInfo(CurrentDirectory);
                //System.Func<FileInfo, BrowseItem> process = delegate(FileInfo fi)
                //{
                //    return new BrowseItem() { Name = fi.FullName.Replace(_RootDirectory, "") };
                //};
               
                result.Add(new BrowseItem() { Name = "..", Path = Path.GetDirectoryName(di.FullName), IsDirectory = true, Icon = UPDIRICON });
                
                // Add all files at this directory to the result List.
                result.AddRange(di.GetDirectories().Select(item => new BrowseItem() { IsDirectory = true, Path = Path.GetDirectoryName(item.FullName), Name = item.Name, Icon = DIRICON }).ToArray());
                result.AddRange(di.GetFiles().Select(item => new BrowseItem() { Name = item.FullName.Replace(_RootDirectory, "") }).ToArray());
            }
            catch
            {
                // Could not open the directory
            }
            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            return jss.Serialize(result);
            
        }
        
        
    }
}